package cn.tedu.cart.service;

import cn.tedu.cart.mapper.CartMapper;
import cn.tedu.product.api.ProductApi;
import com.jt.common.pojo.Cart;
import com.jt.common.pojo.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Service
public class CartService {
    @Autowired(required = false)
    private CartMapper cartMapper;
    /*@Autowired
    private RestTemplate restTemplate;*/
    public List<Cart> queryMycarts(String userId) {
        return cartMapper.selectCartsByUserid(userId);
    }
    @Autowired
    private ProductApi productApi;
    public void addCart(Cart cart) {
        //查询已存在
        Cart exist = cartMapper.selectCartByUseridAndProductid(cart);
        if(exist == null){
            //insert新增  调用微服务
            /*String url = "http://product-service/product/manage/item/"+cart.getProductId();
            Product product = restTemplate.getForObject(url, Product.class);*/
            Product product = productApi.queryOneProduct(cart.getProductId());
            productApi.queryByPage(1,5);
            cart.setProductName(product.getProductName());
            cart.setProductImage(product.getProductImgurl());
            cart.setProductPrice(product.getProductPrice());
            cartMapper.insertCart(cart);
        }else {
            //已有该购物车
            cart.setNum(cart.getNum()+exist.getNum());
            cartMapper.updateNumByUseridAndProductid(cart);
        }
    }

    public void updateCartNum(Cart cart) {
        cartMapper.updateNumByUseridAndProductid(cart);
    }

    public void deleteCart(Cart cart) {
        cartMapper.deleteCartByUseridAndProductid(cart);
    }
}
